package com.itranswarp.learnjava.filters;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itranswarp.learnjava.bean.Permission;
import com.itranswarp.learnjava.utils.Response;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import com.itranswarp.learnjava.dao.PermissionDAO;
import com.itranswarp.learnjava.bean.User;

import com.itranswarp.learnjava.utils.CachedHttpServletResponse;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebFilter(urlPatterns = "/*")
public class IndexFilter implements Filter {

    private boolean validateUser(HttpSession session){
        var user = (User) session.getAttribute("user");
        return user != null;
    }

    public static void writeJson(HttpServletResponse resp, int status, String json) throws IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setStatus(status);
        PrintWriter out = resp.getWriter();
        out.write(json);
        out.flush();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        HttpSession session = req.getSession();

        // 跳过静态资源
        if (uri.contains("/login") || uri.contains("/siginin")||uri.matches(".*\\.(css|js|png|jpg|jpeg|gif|ico|woff2?|ttf|svg|eot|html)$")) {
            chain.doFilter(request, response); // 放行，不处理
            return;
        }
        if(!this.validateUser(session)){
            System.out.println("未登录，重定向");
            ((HttpServletResponse) response).sendRedirect("/login");
            return;
        }

        if(uri.contains("/api")){
            var user = (User) session.getAttribute("user");
            ArrayList<Permission> permissions = new ArrayList<>();
            permissions = PermissionDAO.getPermissionsById((int) user.id);

            boolean hasAuth = permissions.stream().anyMatch(permission -> uri.equals("/api/"+permission.code));
            System.out.println("处理动态请求: " + uri);

            if(!hasAuth){
//                CachedHttpServletResponse wrapper = new CachedHttpServletResponse((HttpServletResponse) response);
                writeJson((HttpServletResponse) response, 200, "{\"code\":403,\"info\":\"暂无该权限\"}");
                return;
            }
            // 其它请求处理逻辑
            System.out.println(hasAuth);
            chain.doFilter(request, response);
            return;
        }
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
